package com.lch.designpattern.singleton;

import com.lch.designpattern.singleton.register.EnumSingleton;


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author: liuchenhui
 * @create: 2019-04-17 00:13
 **/
public class EnumSingletonTest {
    public static void main(String[] args) {
        EnumSingleton singleton1 = null;
        EnumSingleton singleton2 = EnumSingleton.getInstance();
        singleton2.setData(new Object());

        try {
            FileOutputStream fos = new FileOutputStream("seriable.obj");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(singleton2);
            oos.flush();
            oos.close();

            FileInputStream fis = new FileInputStream("seriable.obj");
            ObjectInputStream ois = new ObjectInputStream(fis);
            singleton1 = (EnumSingleton) ois.readObject();
            ois.close();

            System.out.println(singleton1);
            System.out.println(singleton2);
            System.out.println(singleton1.getData() == singleton2.getData());
        } catch (Exception e) {

        }
//        test();
    }

    public static void test() {
        try {
            Class clazz = EnumSingleton.class;
            Constructor constructor = clazz.getDeclaredConstructor(String.class, int.class);
            constructor.setAccessible(true);

            constructor.newInstance();
        }  catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
